
import traceback
import sys
import logging

import destination

from config import *

logger = logging.getLogger('dmzwatch.'+__name__)

def dmzwatch_error(message, severity, exctype, excvalue, exctrace):

    exceptionerror = ''
    for line in traceback.format_exception_only(exctype, excvalue):
        exceptionerror = exceptionerror + line
    
    description = 'Internal dmzwatch error. Severity: {}, Message: {}, Exception: {}'.format(severity, message, exceptionerror)
    
    exceptionerror = ''
    for line in traceback.format_exception(exctype, excvalue, exctrace):
        exceptionerror = exceptionerror + line
        
    extended_description = 'Internal dmzwatch error. Severity: {}, Message: {}, Exception: {}'.format(severity, message, exceptionerror)
    logger.error(extended_description)
    send(IncidentType.dmzwatch_internal_error, severity, description)


def send(type, severity, msg):
    
    try:
        if severity == Severity.high:
            destination_types =  destination_by_type()['high_severity']
            
        elif type not in destination_by_type().keys():
            destination_types = destination_by_type()['default']
            
        else:
            destination_types = destination_by_type()[type]
    except:
        double_panic([type, severity, msg], 'Destination handler is not defined', *sys.exc_info())
        
    else:
        try:
            dstfunctions = []
            for dt in destination_types:
                dstfunctions.append(getattr(destination, dt))
        except:
                double_panic([type, severity, msg], 'Cannot find appropriate destination handler, PANIC!', *sys.exc_info())
                
        else:
            for df in dstfunctions:
                try:
                    df(type, severity, msg)
                except:
                    double_panic([type, severity, msg], 'Error during sending report, panic?',  *sys.exc_info())
        

def double_panic(first_error_details, second_error_description, exctype, excvalue, exctrace):
    logger.debug('---------------------')
    logger.debug('incident, within an incident, within an incident, withi')
    for line in traceback.format_exception(exctype, excvalue, exctrace):
        logger.error('%s', line)
    logger.debug('---------------------')
 
